<template>
  <div class="admin-manage">
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">
        新增管理员
      </el-button>
      <FilterBar
        :searchQuery="searchQuery"
        showSearch
        :isAdmin="true"
        @update:searchQuery="searchQuery = $event"
      />
    </div>

    <LoadingWrapper :loading="loading">
      <div>
        <el-table 
          v-if="adminList.length > 0"
          :data="paginatedAdmins" 
          style="width: 100%" 
          :cell-style="{ padding: '12px 0' }"
        >
          <el-table-column 
            label="序号" 
            width="80"
            align="center"
          >
            <template #default="scope">
              {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          
          <el-table-column 
            prop="id" 
            label="ID" 
            width="80"
            align="center"
            v-if="false"
          />
          
          <el-table-column 
            prop="username" 
            label="用户名" 
            width="180"
            align="center"
            show-overflow-tooltip
          />

          <el-table-column 
            prop="nickname" 
            label="昵称" 
            width="180"
            align="center"
            show-overflow-tooltip
          />
          
          <el-table-column 
            prop="permissions" 
            label="权限" 
            min-width="200"
            align="center"
          >
            <template #default="scope">
              <el-tag
                v-for="perm in scope.row.permissions"
                :key="perm.id"
                class="permission-tag"
                :type="perm.type"
              >
                {{ perm.name }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column 
            prop="createTime" 
            label="创建时间" 
            width="180"
            align="center"
          >
            <template #default="scope">
              {{ formatDateTime(scope.row.created_at) }}
            </template>
          </el-table-column>
          
          <el-table-column 
            label="操作" 
            width="180" 
            fixed="right"
            align="center"
          >
            <template #default="scope">
              <div class="operation-cell">
                <el-tooltip 
                  :content="scope.row.is_super ? '系统管理员不可操作' : '编辑'" 
                  placement="top"
                  :show-after="0"
                  :hide-after="0"
                >
                  <div class="button-wrapper" :class="{ 'disabled': scope.row.is_super }">
                    <el-button 
                      type="primary" 
                      link 
                      @click="handleEdit(scope.row)"
                      :disabled="scope.row.is_super"
                    >
                      <el-icon><Edit /></el-icon>
                    </el-button>
                  </div>
                </el-tooltip>

                <el-tooltip 
                  :content="scope.row.is_super ? '系统管理员不可操作' : '设置权限'" 
                  placement="top"
                  :show-after="0"
                  :hide-after="0"
                >
                  <div class="button-wrapper" :class="{ 'disabled': scope.row.is_super }">
                    <el-button 
                      type="info" 
                      link 
                      @click="handleSetPermissions(scope.row)"
                      :disabled="scope.row.is_super"
                    >
                      <el-icon><Setting /></el-icon>
                    </el-button>
                  </div>
                </el-tooltip>

                <el-tooltip 
                  :content="scope.row.is_super ? '系统管理员不可操作' : '删除'" 
                  placement="top"
                  :show-after="0"
                  :hide-after="0"
                >
                  <div class="button-wrapper" :class="{ 'disabled': scope.row.is_super }">
                    <el-button 
                      type="danger" 
                      link 
                      @click="handleDelete(scope.row)"
                      :disabled="scope.row.is_super"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-else description="暂无数据" />
      </div>
    </LoadingWrapper>

    <div class="pagination-wrapper">
      <PaginationBar
        v-if="adminList.length > 0"
        v-model:currentPage="currentPage"
        v-model:pageSize="pageSize"
        :total="adminList.length"
        :pageSizes="[10, 15, 20, 25]"
        @pagination-change="handlePaginationChange"
      />
    </div>

    <!-- 添加管理员对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加管理员"
      width="500px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="adminFormRef"
        :model="adminForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="adminForm.username" 
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="adminForm.password" 
            type="password" 
            show-password 
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="adminForm.confirmPassword" 
            type="password" 
            show-password 
            placeholder="请再次输入密码"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="设置权限"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form label-width="100px">
        <el-form-item label="权限选择">
          <el-checkbox-group 
            v-model="selectedPermissions"
            @change="handlePermissionChange"
          >
            <el-checkbox 
              v-for="perm in availablePermissions" 
              :key="perm.id" 
              :label="perm.id"
              :disabled="currentEditingAdmin?.is_super || 
                        (perm.id === 1 && selectedPermissions.length > 0 && !selectedPermissions.includes(1)) ||
                        (perm.id !== 1 && selectedPermissions.includes(1))"
            >
              {{ perm.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handlePermissionSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑管理员对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑管理员"
      width="500px"
      :before-close="handleEditDialogClose"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="editForm.username" 
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="editForm.newPassword" 
            type="password" 
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleEditDialogClose">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete, Setting } from '@element-plus/icons-vue'
import { getAdminList, addAdmin, updateAdmin, deleteAdmin, updateAdminPermissions } from '@/api/admin'
import { useAdminStore } from '@/stores/admin'
import { formatDateTime } from '@/utils/format'
import FilterBar from '@/components/filter/FilterBar.vue'
import PaginationBar from '@/components/pagination/PaginationBar.vue'
import LoadingWrapper from '@/components/loading/LoadingWrapper.vue'

const adminStore = useAdminStore()
const adminList = ref([])
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const currentAdminId = ref(null)
const adminFormRef = ref(null)
const selectedPermissions = ref([])
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = ref({
  id: null,
  username: '',
  newPassword: '',
  originalUsername: ''
})
const adminForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
  originalUsername: '',
  originalNickname: ''
})
const searchQuery = ref('')

// 可用权限列表
const availablePermissions = [
  { id: 1, name: '超级管理员', type: 'danger' },
  { id: 2, name: '数据看板', type: '' },
  { id: 3, name: '书籍管理', type: 'success' },
  { id: 4, name: '举报管理', type: 'info' },
  { id: 5, name: '用户管理', type: 'warning' }
]

// 添加 loading 状态
const loading = ref(true)

// 加载管理员列表
const loadAdminList = async () => {
  try {
    loading.value = true
    const res = await getAdminList()
    if (res.code === 200) {
      adminList.value = res.data.map((admin, index) => ({
        ...admin,
        index: index + 1,
        permissions: admin.permissions || []
      }))
    } else {
      ElMessage.error(res.message || '获取管理员列表失败')
    }
  } catch (error) {
    console.error('获取管理员列表失败:', error)
    ElMessage.error('获取管理员列表失败')
  } finally {
    loading.value = false
  }
}

// 添加管理员
const handleAdd = () => {
  adminForm.value = {
    username: '',
    password: '',
    confirmPassword: '',
    originalUsername: '',
    originalNickname: ''
  }
  if (adminFormRef.value) {
    adminFormRef.value.resetFields()
  }
  dialogVisible.value = true
}

// 删除管理员
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('删除后将无法恢复，是否继续？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteAdmin(row.id)
    ElMessage.success('删除成功')
    // 重新加载列表
    loadAdminList()
    
  } catch (error) {
    if (error === 'cancel') return
    ElMessage.error('删除失败，请稍后重试')
  }
}

// 设置权限
const handleSetPermissions = (admin) => {
  currentEditingAdmin.value = admin
  // 直接设置初始权限，不触发 watch
  selectedPermissions.value = admin.permissions?.map(p => p.id) || []
  permissionDialogVisible.value = true
}

// 处理权限提交
const handlePermissionSubmit = async () => {
  if (!currentEditingAdmin.value) {
    ElMessage.warning('请选择要设置权限的管理员')
    return
  }

  try {
    await updateAdminPermissions(currentEditingAdmin.value.id, selectedPermissions.value)
    ElMessage.success('权限设置成功')
    await loadAdminList()
    handleDialogClose()
  } catch (error) {
    console.error('设置权限失败:', error)
    ElMessage.error('权限设置失败')
  }
}

// 提交表单 - 新增管理员
const handleSubmit = async () => {
  if (!adminFormRef.value) return
  
  try {
    await adminFormRef.value.validate()
    
    const response = await addAdmin({
      username: adminForm.value.username,
      password: adminForm.value.password,
      nickname: adminForm.value.username
    })

    if (response.code === 200) {
      // 关闭对话框
      dialogVisible.value = false
      ElMessage.success('添加成功')
      // 重新加载数据
      await loadAdminList()
    } else {
      ElMessage.error(response.message)
    }
    
  } catch (error) {
    if (error.response?.data) {
      ElMessage.error(error.response.data.message || '操作失败')
    } else {
      ElMessage.error(error.message || '操作失败')
    }
  }
}

// 处理对话框关闭
const handleDialogClose = () => {
  dialogVisible.value = false
  adminFormRef.value?.resetFields()
  permissionDialogVisible.value = false
  currentEditingAdmin.value = null
  selectedPermissions.value = []
}

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]+$/, message: '用户名只能包含字母和数字', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 10, message: '密码长度在 6 到 10 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]+$/, message: '密码只能包含字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== adminForm.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 编辑表单验证规则
const editRules = {
  username: [
    { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' },
    { 
      pattern: /^[a-zA-Z0-9]+$/, 
      message: '用户名只能包含字母和数字', 
      trigger: 'blur' 
    }
  ],
  newPassword: [
    { min: 6, max: 10, message: '密码长度在 6 到 10 个字符', trigger: 'blur' },
    { 
      pattern: /^[a-zA-Z0-9]+$/, 
      message: '密码只能包含字母和数字', 
      trigger: 'blur' 
    }
  ]
}

// 编辑管理员
const handleEdit = (row) => {
  editForm.value.id = row.id;
  editForm.value.username = row.username;
  editForm.value.originalUsername = row.username;
  editForm.value.newPassword = '';
  editDialogVisible.value = true;
};

// 关闭编辑对话框
const handleEditDialogClose = () => {
  if (editForm.value.username || editForm.value.newPassword) {
    ElMessageBox.confirm(
      '确认关闭？未保存的内容将会丢失',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
      .then(() => {
        editDialogVisible.value = false
        editForm.value = {
          id: null,
          username: '',
          newPassword: '',
          originalUsername: ''
        }
        if (editFormRef.value) {
          editFormRef.value.resetFields()
        }
      })
      .catch(() => {
        // 用户取消关闭
      })
  } else {
    editDialogVisible.value = false
    editForm.value = {
      id: null,
      username: '',
      newPassword: '',
      originalUsername: ''
    }
    if (editFormRef.value) {
      editFormRef.value.resetFields()
    }
  }
}

// 提交编辑表单
const handleEditSubmit = async () => {
  if (!editFormRef.value) return;

  try {
    await editFormRef.value.validate();

    // 构建更新数据
    const updateData = {
      username: editForm.value.username
    };
    // 如果设置了新密码，添加到更新数据中
    if (editForm.value.newPassword) {
      updateData.password = editForm.value.newPassword;
    }

    const response = await updateAdmin(editForm.value.id, updateData);

    if (response.code === 200) {
      // 关闭对话框
      editDialogVisible.value = false;
      ElMessage.success('更新成功');
      // 重新加载数据
      await loadAdminList();
    } else {
      ElMessage.error(response.message);
    }

  } catch (error) {
    if (error.response?.data) {
      ElMessage.error(error.response.data.message || '操作失败');
    } else {
      ElMessage.error(error.message || '操作失败');
    }
  }
};

// 使用 watch 监听管理员信息变化
watch(() => adminStore.adminInfo, (newValue, oldValue) => {
  if (newValue !== oldValue) {
    loadAdminList();
  }
});

// 在组件挂载时获取数据
onMounted(() => {
  loadAdminList();
});

// 获取操作提示文本
const getOperationTooltip = (operation, isFirst) => {
  if (isFirst) {
    return '系统管理员不可操作'
  }
  const tooltips = {
    edit: '编辑',
    permission: '设置权限',
    delete: '删除'
  }
  return tooltips[operation]
}

const isSuperAdmin = computed(() => {
  return selectedPermissions.value.includes(1)
})

const handleUpdateAdmin = async () => {
  try {
    await updateAdmin(editForm.value)
    ElMessage.success('更新成功')
    adminStore.updateAdminInfo(editForm.value)
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

// 处理权限变化
const handlePermissionChange = (newVal) => {
  if (!Array.isArray(newVal)) {
    selectedPermissions.value = []
    return
  }

  if (newVal.includes(1)) {
    // 如果选择了超级管理员，只保留超级管理员
    if (newVal.length > 1) {
      selectedPermissions.value = [1]
    }
  } else if (selectedPermissions.value.includes(1)) {
    // 如果取消了超级管理员，清空所有选择
    selectedPermissions.value = []
  }
}

const currentEditingAdmin = ref(null)
const isSystemAdmin = computed(() => currentEditingAdmin.value?.id === 1)

// 过滤管理员列表
const filteredAdmins = computed(() => {
  return adminList.value.filter(admin => {
    return !searchQuery.value || 
      admin.username.toLowerCase().includes(searchQuery.value.toLowerCase())
  })
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 分页后的管理员列表
const paginatedAdmins = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredAdmins.value.slice(start, end)
})

// 处理分页变化
const handlePaginationChange = ({ type, value }) => {
  if (type === 'page') {
    currentPage.value = value
  } else if (type === 'size') {
    pageSize.value = value
    currentPage.value = 1
  }
}

// 监听搜索条件变化，重置页码
watch(searchQuery, () => {
  currentPage.value = 1
})
</script>

<style scoped>
.admin-manage {
  padding: 20px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.operation-cell {
  display: flex;
  justify-content: center;
  gap: 12px;
  
  .el-button {
    margin: 0;
  }
}

.permission-tag {
  margin: 0 4px;
  
  &[type="danger"] {
    background-color: var(--el-color-danger-light-9);
    border-color: var(--el-color-danger-light-7);
    color: var(--el-color-danger);
  }
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.el-button {
  padding: 8px 12px;
}

.el-icon {
  font-size: 18px;
}

/* 调整按钮间距 */
.el-table .cell {
  .el-button + .el-button {
    margin-left: 12px;
  }
}

.button-wrapper {
  display: inline-block;
  
  &.disabled {
    cursor: not-allowed;
    opacity: 0.6;
    
    :deep(.el-button) {
      cursor: not-allowed;
      
      .el-icon {
        color: var(--el-text-color-disabled);
      }
    }
    
    &:hover {
      opacity: 0.6;
    }
  }
}

/* 使用深度选择器来修改表头样式 */
:deep(.status-column-header) {
  padding-right: 40px !important;
}

:deep(.filter-bar) {
  margin-bottom: 0;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.pagination-wrapper :deep(.el-pagination) {
  display: flex;
  justify-content: flex-end;
}
</style> 